import { createStore } from 'vuex'

export default createStore({
  state: {
    userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}'),
    isLoggedIn: !!localStorage.getItem('userInfo')
  },
  mutations: {
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
      state.isLoggedIn = !!userInfo.token
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    },
    CLEAR_USER_INFO(state) {
      state.userInfo = {}
      state.isLoggedIn = false
      localStorage.removeItem('userInfo')
    }
  },
  actions: {
    login({ commit }, userInfo) {
      return new Promise((resolve) => {
        commit('SET_USER_INFO', userInfo)
        resolve()
      })
    },
    logout({ commit }) {
      return new Promise((resolve) => {
        commit('CLEAR_USER_INFO')
        resolve()
      })
    }
  },
  getters: {
    userInfo: state => state.userInfo,
    isLoggedIn: state => state.isLoggedIn,
    isAdmin: state => state.userInfo.role === 'ADMIN',
    isVisitor: state => state.userInfo.role === 'VISITOR'
  }
}) 